package com.heiyu.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;

public class SHAUtils {

	private static final String ALGORITHM_SHA1 = "SHA1";
	private static final char[] HexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	private final static Logger logger = LoggerFactory.getLogger(SHAUtils.class);

	//签名
	public static String sign(List<String> params) {
		if (params == null || params.size() == 0) {
			return null;
		}
		StringBuilder waitSign = new StringBuilder();
		Collections.sort(params);
		for (String param : params) {
			waitSign.append(param);
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM_SHA1);
			messageDigest.update(waitSign.toString().getBytes("utf-8"));
			byte[] bytes = messageDigest.digest();
			int len = bytes.length;
			waitSign = new StringBuilder(len * 2);
			for (int j = 0; j < len; j++) {
				waitSign.append(HexDigits[(bytes[j] >> 4) & 0x0f]);
				waitSign.append(HexDigits[bytes[j] & 0x0f]);
			}
			return waitSign.toString();
		} catch (Exception e) {
			logger.error("rsa签名错误", e);
		}
		return null;
	}

	//验签
	public static boolean checkSign(List<String> params, String sign) {
		String newSign = sign(params);
		return newSign.equals(sign);
	}
}
